import { useEffect, useState } from "react";
import { defaultSkuList, getUniqueListByKey, removeSpacesAndConvertToLowerCase } from "../utils";
import { cloneDeep } from "lodash";
import { Button, Cascader, message } from "antd";

import {
	goodsSkuMatch,
	getZjfGoodsSkuVOList,
	getMatchSkuListBySpuId,
	foreignSeniorSearchByUrl,
	getSupplierSpuList
} from "../service";

export const useSkuList = ({ spuId, onDrawerClose, Separator }) => {
	const [skuList, setSkuList] = useState([...defaultSkuList]); //可匹配的接口数据（含 colour 和 specs ）
	const [skuColorList, setSkuColorList] = useState([]); // 系统商品sku， 颜色不重复
	const [skuSizeList, setSkuSizeList] = useState([]); // 系统商品sku， 尺码不重复
	const [dataSource, setDataSource] = useState([]); //
	const [sizeDataSource, setSizeDataSource] = useState([]); //	// 在此需要使用 ，在 useSizeList 也需要使用，所以定义在此

	const [storeSpuSelected, setStoreSpuSelected] = useState([]);
	const [storeSpuSelectedAllSku, setStoreSpuSelectedAllSku] = useState([]);
	const [storeColorOptions, setStoreColorOptions] = useState([]);

	const [selectOptionsMap, setSelectOptionsMap] = useState({});
	useEffect(() => {
		const o = {};
		storeSpuSelectedAllSku.forEach(e => {
			const { storeId, goodsCommonId, size, color, goodsId, goodsName, storeName } = e;
			const code = `${storeId}${Separator}${goodsCommonId}`;
			if (o[code]) {
				o[code] = Array.from(new Set([...o[code], size]));
			} else {
				o[code] = [size];
			}
		});
		setSelectOptionsMap(o);
	}, [storeSpuSelectedAllSku]);

	useEffect(() => {
		getMatchSkuListBySpuId({ id: spuId }).then(({ success, data }) => {
			if (data.every(e => e.colour && e.specs) && data.length) {
				setSkuList(data);
			} else {
				message.warning("该商品不支持高级匹配");
				onDrawerClose(null, false);
			}
		});
	}, []);

	useEffect(() => {
		const __skuColorList = getUniqueListByKey(skuList, "colour", "supplierId");
		const __skuSizeList = getUniqueListByKey(skuList, "specs", "supplierId");

		setSkuSizeList(__skuSizeList);
		setSkuColorList(__skuColorList);

		setDataSource(
			__skuColorList.map(e => {
				return {
					...e,
					sysColor: e.colour,
					storeColor: ""
				};
			})
		);

		// 获取默认配置的sku信息
		const matchedStoreSkuList = skuList.filter(e => e.supplierSpuCode);
		const matchedStoreSpuIds = getUniqueListByKey(matchedStoreSkuList, "supplierSpuCode", "supplierId").map(
			e => e.supplierSpuCode
		);
		if (matchedStoreSpuIds.length) {
			getSupplierSpuList({ goodsCommonIdList: matchedStoreSpuIds, pageSize: 1000, size: 1000, current: 1, pageNum: 1 }).then(
				({ data, success }) => {
					console.log(data, success);
					const supplierSpuList = data?.records;
					if (success && Array.isArray(supplierSpuList)) {
						handleSupplierSpuModalOk(supplierSpuList, { __skuColorList, __skuSizeList });
					}
				}
			);
		}
	}, [skuList]);

	const handleSupplierSpuModalOk = (selectedStoreSpuRows, isDefaultObj = false) => {
		console.log("handleSupplierSpuModalOk", selectedStoreSpuRows);
		const spuIds = [];
		setStoreSpuSelected(pre => {
			const __pre = cloneDeep(pre);
			selectedStoreSpuRows.forEach(selectedStoreSpuRow => {
				if (!pre.find(e => e.goodsCommonid == selectedStoreSpuRow.goodsCommonid)) {
					__pre.push(selectedStoreSpuRow);
					spuIds.push(selectedStoreSpuRow.goodsCommonid);
				}
			});
			if (spuIds.length) {
				getZjfGoodsSkuVOList({ goodsCommonIdList: spuIds }).then(({ data: resStoreSkuList, success }) => {
					if (success && Array.isArray(resStoreSkuList)) {
						setStoreSpuSelectedAllSku(preStoreSkuList => {
							const __preStoreSkuList = cloneDeep(preStoreSkuList);
							resStoreSkuList.forEach(resStoreSkuRow => {
								if (!__preStoreSkuList.find(e => e.goodsId == resStoreSkuRow.goodsId)) {
									__preStoreSkuList.push(resStoreSkuRow);
								}
							});

							// 模拟 handleStoreSpuColorChange 选中颜色
							if (isDefaultObj) {
								const { __skuColorList, __skuSizeList } = isDefaultObj;
								setTimeout(() => {
									__skuColorList
										.filter(e => e.supplierSpuCode)
										.forEach(record => {
											setDataSource(pre => {
												const __pre = cloneDeep(pre);
												__pre.forEach(item => {
													if (item.sysColor === record.colour) {
														const storeRow = __preStoreSkuList.find(e => String(e.goodsId) === String(record.supplierSkuId));
														if (storeRow) {
															const {
																storeId,
																storeName,
																goodsCommonId: storeSpuId,
																color: storeColor,
																size: storeSize
															} = storeRow;
															const storeSpu = selectedStoreSpuRows.find(e => String(e.goodsCommonid) === String(storeSpuId));
															const v = [storeId, storeSpuId, storeColor];
															item.storeColor = storeColor;
															item.cascaderValue = v;
															item.matchStore = {
																storeId,
																storeName,
																storeSpuId,
																storeSpuName: storeSpu?.goodsName,
																storeColor
															};
															// 模拟 useSizeList handleChange 选中尺码
															const code = `${storeId}${Separator}${storeSpuId}`;
															setSizeDataSource(pre => {
																const __pre = cloneDeep(pre);
																__pre.forEach(item => {
																	item[code] = storeSize;
																});

																return __pre;
															});
														}
													}
												});

												return __pre;
											});
										});
								}, 1);
							}

							return __preStoreSkuList;
						});
					}
				});
			}

			return [...__pre];
		});
	};

	useEffect(() => {
		const options = [];

		const colorsOptions = goodsCommonId => {
			const temp = storeSpuSelectedAllSku
				.filter(sku => sku.goodsCommonId == goodsCommonId)
				.map(e => ({ value: e.color, label: e.color }));
			return getUniqueListByKey(temp, "value");
		};

		storeSpuSelected.forEach(row => {
			const i = options.findIndex(e => e.value == row.storeId);
			if (i == -1) {
				options.push({
					value: row.storeId,
					label: row.storeName,
					children: [
						{
							value: row.goodsCommonid,
							label: row.goodsName,
							children: colorsOptions(row.goodsCommonid)
						}
					]
				});
			} else {
				options[i].children.push({
					value: row.goodsCommonid,
					label: row.goodsName,
					children: colorsOptions(row.goodsCommonid)
				});
			}
		});

		setStoreColorOptions(options);
	}, [storeSpuSelected, storeSpuSelectedAllSku]);

	const handleStoreSpuColorChange = (v, selectedOptions, record, index) => {
		console.log("handleStoreSpuColorChange1", v, selectedOptions);
		console.log("handleStoreSpuColorChange2", selectedOptions, record, index);
		const [storeId, storeSpuId, storeColor] = v;
		const [storeOption, spuOption, colorOption] = selectedOptions;
		setDataSource(pre => {
			const __pre = cloneDeep(pre);
			__pre.forEach(item => {
				if (item.sysColor === record.sysColor) {
					item.storeColor = storeColor;
					item.cascaderValue = v;
					item.matchStore = {
						storeId,
						storeName: storeOption.label,
						storeSpuId,
						storeSpuName: spuOption.label,
						storeColor
					};
				}
			});

			return __pre;
		});
	};
	const handleCommand = (TEXT, record) => {
		if (TEXT == "一键匹配") {
			const { storeId, storeSpuId } = record.matchStore;
			const code = `${storeId}${Separator}${storeSpuId}`;
			setSizeDataSource(pre => {
				const __pre = cloneDeep(pre);
				__pre.forEach(item => {
					const sysSpecs = removeSpacesAndConvertToLowerCase(item.sysSpecs);
					const options = selectOptionsMap[code] || [];
					options.find(size => {
						const _ov = removeSpacesAndConvertToLowerCase(size);
						if (sysSpecs == _ov) {
							item[code] = size;
						}
					});
				});

				return __pre;
			});
		}
		if (TEXT == "清空") {
			setDataSource(pre => {
				const __pre = cloneDeep(pre);
				__pre.forEach(item => {
					if (item.sysColor === record.sysColor) {
						item.storeColor = null;
						item.cascaderValue = [];
						item.matchStore = null;
					}
				});

				return __pre;
			});
		}
	};

	const tableKey = "SystemGoodsMatchSeniorMatchTableSku";
	const columns = [
		{
			name: "颜色",
			code: "sysColor",
			width: "20%"
		},
		{
			name: () => <></>,
			code: "cascaderValue",
			width: "50%",
			render: (cascaderValue, record, index) => {
				return (
					<Cascader
						value={cascaderValue}
						className="width-full"
						options={storeColorOptions}
						placeholder="待匹配"
						onChange={(v, selectedOptions) => {
							handleStoreSpuColorChange(v, selectedOptions, record, index);
						}}
					/>
				);
			}
		},
		{
			name: () => <></>,
			code: "action",
			width: "30%",
			align: "center",
			render(_, record) {
				return (
					<>
						<Button disabled={!record.cascaderValue} type="link" onClick={() => handleCommand("一键匹配", record)}>
							一键匹配
						</Button>
						<Button disabled={!record.cascaderValue} type="link" onClick={() => handleCommand("清空", record)}>
							清空
						</Button>
					</>
				);
			}
		}
	];
	const searchSimpleTableProps = {
		tableKey,
		rowKey: "uuid",
		// ///
		dataSource,
		columns,
		footer: false
	};
	return {
		tableKey,
		searchSimpleTableProps,
		handleSupplierSpuModalOk,
		dataSource,
		skuList,
		skuSizeList,
		selectOptionsMap,
		sizeDataSource,
		setSizeDataSource,
		storeSpuSelected,
		storeSpuSelectedAllSku
	};
};
